package com.thinkit.bigdata.core.util;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by BanAiQin on 2017/3/24.
 * 编码格式工具类
 */
public class EncodingUtil {

    //判断文件编码格式，参数文件名
    public static String getCharset(String fileName) throws IOException {

        BufferedInputStream bin = new BufferedInputStream(new FileInputStream(fileName));
        int p = (bin.read() << 8) + bin.read();
        String code = "";
        switch (p) {
            case 0xefbb:
                code = "UTF-8";
                break;
            case 0xfffe:
                code = "Unicode";
                break;
            case 0xfeff:
                code = "UTF-16BE";
                break;
            default:
                code = "GBK";
        }
        System.out.println("文件" + fileName + "格式：" + code);
        bin.close();
        return code;
    }

    //判断文件编码格式，文件输入流,第一种判断方式
    public static String getCharset(String fileName, InputStream stream) throws IOException {

        BufferedInputStream bin = new BufferedInputStream(stream);
        byte[] head = new byte[3];
        bin.read(head);
        String code = "";
        code = "GBK";
        if (head[0] == -1 && head[1] == -2)
            code = "UTF-16";
        if (head[0] == -2 && head[1] == -1)
            code = "Unicode";
        if (head[0] == -17 && head[1] == -69 && head[2] == -65)
            code = "UTF-8";
        System.out.println(code);
        bin.close();
        return code;
    }


    //判断文件编码格式，文件输入流,第二种判断方式
    public static String getCharset2(String fileName, InputStream stream) throws IOException {

        BufferedInputStream bin = new BufferedInputStream(stream);
        int p = (bin.read() << 8) + bin.read();
        String code = "";

        switch (p) {
            case 0xefbb:
                code = "UTF-8";
                break;
            case 0xfffe:
                code = "Unicode";
                break;
            case 0xfeff:
                code = "UTF-16BE";
                break;
            default:
                code = "GBK";
        }
        System.out.println("文件" + fileName + "格式：" + code);
        bin.close();
        return code;
    }
}
